package com.wmyg.scanninggun.typehandle;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.*;

@MappedTypes({String[].class})
@MappedJdbcTypes({JdbcType.VARCHAR})
public class StringArrayTypeHandler implements TypeHandler<String[]> {

    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, String[] strings, JdbcType jdbcType) throws SQLException {
        if (strings == null) {
            preparedStatement.setNull(i, Types.VARCHAR);
        } else {
            StringBuffer result = new StringBuffer();
            for (String s :
                    strings) {
                result.append(s).append(",");
            }
            result.deleteCharAt(result.length() - 1);
            preparedStatement.setString(i, result.toString());
        }
    }

    @Override
    public String[] getResult(ResultSet resultSet, String s) throws SQLException {
        s = resultSet.getString(s);
        return getStringArray(s);
    }

    @Override
    public String[] getResult(ResultSet resultSet, int i) throws SQLException {
        String s = resultSet.getString(i);
        return getStringArray(s);
    }

    @Override
    public String[] getResult(CallableStatement callableStatement, int i) throws SQLException {
        String s = callableStatement.getString(i);
        return getStringArray(s);
    }

    private String[] getStringArray(String columnValue) {
        if (columnValue == null) {
            return null;
        }
        return columnValue.split(",");
    }

}
